package com.bean;

import java.net.InetAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Value;

public class ClientFactory implements FactoryBean<TransportClient>, DisposableBean {

//	private static final Logger logger = LoggerFactory.getLogger(ClientFactory.class);
	private volatile TransportClient client;

	// 占位符方式
	@Value("${host}")
	private String host;
	// 使用SpeEL方式
	@Value("#{env.getProperty('port')}")
	private String port;

	@Value("${clusterName}")
	private String clusterName;

	public ClientFactory() {
	}

	@SuppressWarnings("resource")
	@Override
	public TransportClient getObject() throws Exception {
		// spring会控制单例的并发安全
		// if (client == null) {
		// synchronized (this) {
		// if (client == null) {
		// try {
		// Settings settings =
		// Settings.builder().put("cluster.name", "jftt")
		// .put("client.transport.sniff", "false").build();
		// client = new
		// PreBuiltTransportClient(settings).addTransportAddress(
		// new TransportAddress(InetAddress.getByName(host),
		// Integer.parseInt(port)));
		// } catch (UnknownHostException e) {
		// logger.error("UnknownHostException in getClient",
		// e);
		// }
		// }
		// }
		// }
		Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", "false")
				.build();
		client = new PreBuiltTransportClient(settings)
				.addTransportAddress(new TransportAddress(InetAddress.getByName(host), Integer.parseInt(port)));
		return client;
	}

	@Override
	public Class<?> getObjectType() {
		return TransportClient.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void destroy() throws Exception {
		if (client != null)
			client.close();
	}

}
